package com.binguo.api.controller;

import com.binguo.api.response.base.ActionResponse;
import com.binguo.api.response.customer.CustomerVO;
import com.binguo.common.enums.CardType;
import com.binguo.common.util.YPUtil;
import com.binguo.model.api.vo.OrderVO;
import com.binguo.model.mapper.BinguoOrderMapper;
import com.binguo.model.mapper.CustomerMapper;
import com.binguo.model.mapper.PayCardMapper;
import com.binguo.model.model.*;
import com.binguo.model.mybatis.DomainExample;
import com.binguo.model.mybatis.StdDomain;
import com.binguo.model.repository.CustomerRepository;
import com.binguo.model.repository.FaceRepository;
import com.binguo.model.repository.ShopRepository;
import com.binguo.transfer.OrderVOTransfer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.util.*;

@RestController
@RequestMapping
public class OpenController {

    @Resource
    ShopRepository shopRepository;
    @Resource
    PayCardMapper payCardMapper;
    @Resource
    CustomerRepository customerRepository;
    @Resource
    CustomerMapper customerMapper;
    @Resource
    FaceRepository faceRepository;

    @Autowired
    OrderVOTransfer orderVOTransfer;

    @Resource
    BinguoOrderMapper binguoOrderMapper;

    @PostMapping(value = "/api/openapi/getOrderList")
    @ApiOperation(value = "open api,获取用户列表", notes = "")
    public ActionResponse getOrderList(@RequestBody String s){
        try {
            int page = 1;
            Map<String, String> map = YPUtil.xmlToMap(URLDecoder.decode(s, "UTF-8"));
            System.out.println(map.get("nonce_str"));
            System.out.println(map);

            String merchantPhone = map.get("merchantPhone");

            Shop shop = shopRepository.findBy("phone", merchantPhone);
            if (shop == null) {
                return ActionResponse.error("参数错误");
            }

            BinguoOrder binguoOrder = BinguoOrder.builder().build();
            binguoOrder.setShopid(shop.getId());

            StdDomain stdDomain = new StdDomain();
            stdDomain.setPage(1);

            DomainExample<BinguoOrder> example = new DomainExample<>(binguoOrder);
            example.setAddition(stdDomain);

            List<BinguoOrder> binguoOrderList = binguoOrderMapper.findList(example);
            int total = binguoOrderMapper.findOrderCount(example);


            Map<Integer, String> shopNameMap = new HashMap<>();
            shopNameMap.put(shop.getId(), shop.getName());
            List<OrderVO> orderVOList = orderVOTransfer.toOrderVOsNew(binguoOrderList, shopNameMap);

            ActionResponse resp =  ActionResponse.success();
            resp.setPage(page);
            resp.setPageSize(StdDomain.DEFAULT_LIMIT);
            resp.setRows(orderVOList);
            resp.setTotal(total);

            return ActionResponse.success(orderVOList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ActionResponse.error("参数错误");
    }

    @PostMapping(value = "/api/openapi/getUserList")
    @ApiOperation(value = "open api,获取用户列表", notes = "")
    public ActionResponse getUserList(@RequestBody String s){

        int page = 1;
        System.out.println(s);
        try {
            Map<String, String> map = YPUtil.xmlToMap(URLDecoder.decode(s, "UTF-8"));
            System.out.println(map.get("nonce_str"));
            System.out.println(map);

            String merchantPhone = map.get("merchantPhone");

            Shop shop = shopRepository.findBy("phone", merchantPhone);
            if (shop == null) {
                return ActionResponse.error("参数错误");
            }

            PayCard payCard = new PayCard();
            payCard.setCardtype(CardType.BINGUO_CARD.getCode().byteValue());
            payCard.setShopid(shop.getId());

            StdDomain stdDomain = new StdDomain();
            stdDomain.setPage(1);

            DomainExample<PayCard> example = new DomainExample<>(payCard);
            example.setAddition(stdDomain);

            List<Integer> customerIdList = payCardMapper.findCustomerIdList(example);

            if (customerIdList != null && customerIdList.size() > 0) {
                Integer total = payCardMapper.findCustomerIdCount(example);

                String str = StringUtils.join(customerIdList.toArray(), ",");
                List<Customer> customerList = customerMapper.selectByIds(str);

                Condition faceCondition = new Condition(Face.class);
                faceCondition.or().andIn("customerId", customerIdList);
                List<Face> faceList = faceRepository.findByCondition(faceCondition);
                Map<Integer, List<String>> customerFaceListMap = new HashMap<>();
                faceList.stream().forEach(face -> {
                    List<String> faceStrList = customerFaceListMap.get(face.getCustomerId());
                    if (faceStrList == null) {
                        faceStrList = new ArrayList<>();
                    }
                    faceStrList.add(face.getFaceurl());
                    customerFaceListMap.put(face.getCustomerId(), faceStrList);
                });

                List<CustomerVO> result = new ArrayList<>();

                customerList.stream().forEach(customer -> {
                    CustomerVO customerVO = new CustomerVO();
                    customerVO.setCustomerName(customer.getName());
                    customerVO.setCustomerPhone(customer.getPhone());
                    customerVO.setFaceUrlList(customerFaceListMap.get(customer.getId()));

                    result.add(customerVO);
                });

                ActionResponse resp =  ActionResponse.success();
                resp.setPage(page);
                resp.setPageSize(StdDomain.DEFAULT_LIMIT);
                resp.setRows(result);
                resp.setTotal(total);
                return resp;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return ActionResponse.error("参数错误");
    }


}
